
package com.cqvie.controller;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cqvie.service.AccountService;
import com.cqvie.service.StudentService;
import com.cqvie.service.TeacherService;
import com.cqvie.service.UserService;

@Controller
@RequestMapping("/cc")
public class CommonController{

	@Resource
	public StudentService studentService;
	@Resource
	public TeacherService teacherService;
	@Resource
	public UserService userService;
	
	@Resource
	public AccountService accountService;
	
	
	@RequestMapping(value="/login")
	@ResponseBody
	public ResponseMessage logins(
			//HttpServletRequest request,HttpServletResponse response,
			@RequestBody RequestMessage msg,HttpSession httpSession) throws Exception
	{
		ResponseMessage resMsg = new ResponseMessage();
		
		
		msg.proc="userService_isExist";
		Field field = this.getClass().getDeclaredField(msg.getProcClassName());
		Object objService = field.get(this); //!!测试时还没有注入，为null
		Method serviceMethod = MsgProcessor.getMethod(objService, msg.getMethodName());
		if (serviceMethod == null) { // Service中不存在对应方法
			resMsg.status = 0;
			resMsg.desc = msg.getProcClassName() + "中未找到调用方法"
					+ msg.getMethodName();
			return resMsg;
		} // 返回错误信息
		
		Class[] paramTypes = serviceMethod.getParameterTypes();
		Class paramType = paramTypes[0]; // 获得第一个参数的类型
		// msg.data(json格式)转换为对象
		ObjectMapper mapper = new ObjectMapper();
		Object objData = mapper.readValue(msg.data, paramType);
		try {
			Object retObj=null;
			if(paramTypes.length==1)
				retObj = serviceMethod.invoke(objService, objData);
			else if(paramTypes.length==2) //第二个参数为session（用于登录方法，或其他要进行二次用户权限验证的方法）
				retObj = serviceMethod.invoke(objService, objData,httpSession);
			
			resMsg.data = mapper.writeValueAsString(retObj);
			// System.out.println(resMsg.data);
			resMsg.status = 1;
		} catch (Exception ex) {
			resMsg.status = 0;
			resMsg.desc = ex.getMessage();
		}
		
		return resMsg;
	
	}
	
	
	
	//接收内容为json字符串，函数参数加@RequestBody注解（不加就是处理用传统提交方式：application/x-www-form-urlencoded）
	//不清楚为什么没有配置org.springframework.http.converter.json.MappingJacksonHttpMessageConverter也行
	@RequestMapping(value="/json")
	@ResponseBody
	public ResponseMessage testJson(
			//HttpServletRequest request,HttpServletResponse response,
			@RequestBody RequestMessage msg,HttpSession httpSession) throws Exception
	{
		
		System.out.println("@@@@@收到消息：id="+msg.id+"，处理的服务程序："+msg.proc+"，内容："+msg.data);

		//获取spring注入的service对象(负责处理业务的对象)
		//System.out.println(this.getClass().getName());
		Field field = this.getClass().getDeclaredField(msg.getProcClassName());
		Object objService = field.get(this); //!!测试时还没有注入，为null
		
		// check jurisdiction 
		ResponseMessage resMsg = new ResponseMessage();
		if (httpSession.getAttribute("jurisdiction")==null)
			return noPowerReturns(resMsg);
		if (!accountService.accountAccess(msg.getProc(), httpSession)) {
			return noPowerReturns(resMsg);
		}
		return MsgProcessor.process(msg, objService,httpSession);
		
	}
	
	@RequestMapping(value="/test")
	public ResponseMessage test(
			//HttpServletRequest request,HttpServletResponse response,
			) throws Exception
	{
		
		System.out.println("ssssssssssss-----OK-----asdasdasds");
		return null;
	}
	
	
	private static ResponseMessage noPowerReturns(ResponseMessage resMsg) {
		resMsg.status = 1;
		resMsg.data = "No Power";
		return resMsg;
	}
}
